package runtime

import (
	"fmt"
	"runtime"
	"time"
)

func init() {
	runtime.GOMAXPROCS(1) //使用单核
}

func TestGoSched() {
	exit := make(chan int)
	go func() {
		defer close(exit)
		for i := 0; i < 20; i++ {
			fmt.Println("b:", i)
			//time.Sleep(100 * time.Millisecond)
		}
	}()

	for i := 0; i < 20; i++ {
		fmt.Println("a:", i)
		runtime.Gosched() //切换任务
	}

	<-exit
}

//让出CPU时间片，多核go routine轮流执行
func say(s string) {
	for i := 0; i < 2; i++ {
		runtime.Gosched()
		fmt.Println(s)
	}
}
func TestGoSched2() {
	fmt.Println("cpus:", runtime.NumCPU())               // 返回当前系统的CPU核数量
	fmt.Println("goroot:", runtime.GOROOT())             //
	fmt.Println("NumGoroutine:", runtime.NumGoroutine()) // 返回真该执行和排队的任务总数
	fmt.Println("archive:", runtime.GOOS)

	go say("world")
	say("hello")

	time.Sleep(time.Second)
}
